#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string>
#include <cstring>
#include "log.hpp"

using namespace std;

const string pathname = "/home/jby_1";
const int proj_id = 0x6666;
const int size = 4097;
Log log;


#define FIFO_FILE "./myfifo"
#define MODE 0664

enum 
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR,
    FIFO_OPEN_ERR
    
};

key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if(key < 0)
    {
        log(Fatal, "ftok error: %s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success, key is : 0x%x", key);
    return key;
}

int GetShareMemHelper(int flag) 
{   
    key_t key = GetKey();
    int shmid = shmget(key, size, flag);
    if(shmid < 0)
    {
        log(Fatal, "creat share memory error : %s", strerror(errno));
        exit(2);
    }
    log(Info, "creat share memory success, shimid : %d", shmid);
    return shmid;
}       

int CreateShm()
{
    return GetShareMemHelper(IPC_CREAT|IPC_EXCL|0666);
}

int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
} 

class Init
{
public:
    Init()
    {
        //创建一个管道
        int n = mkfifo(FIFO_FILE, MODE);
        if(n == -1) 
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {
        //关闭信道
        int m = unlink(FIFO_FILE);
        if(m == -1)
        {
            perror("unlink:");
            exit(FIFO_DELETE_ERR);
        }
    }

};

#endif



